import { Menu } from 'antd';
import { setLocale, useIntl, history } from 'umi';

import { GlobalOutlined } from '@ant-design/icons';

import React, { useEffect, useState } from 'react';
import classNames from 'classnames';
import HeaderDropdown from '../HeaderDropdown';
import styles from './index.less';
import { getLocal } from '@ey-utils/utils/utils';
import { getLanguagesDictionary } from '@/components/switch-languages/api';
import { setIntl } from '@/utils/i18n-transform';

interface LocalesItem {
  code: string;
  name: string;
}

const LanguagesIcon = {
  zh_CN: '🇨🇳',
  // 'zh-TW': '🇭🇰',
  en_US: '🇬🇧',
  // 'pt-BR': '🇧🇷',
};

interface SelectLangProps {
  className?: string;
}
const SwitchLanguages: React.FC<SelectLangProps> = (props) => {
  const { className } = props;
  const selectedLang = getLocal();

  const [locales, setLocales] = useState<LocalesItem[]>([]);

  const { formatMessage } = useIntl();

  const changeLang = async ({ key }: any) => {
    setLocale(key.split('_').join('-'), false);

    setIntl()

    history.go(0);
  };

  useEffect(() => {
    getLanguagesDictionary().then((res) => {
      const { result, success } = res;

      if (!success) return;

      setLocales(result.filter((item) => item.code));
    });
  }, []);

  const langMenu = (
    <Menu className={styles.menu} selectedKeys={[selectedLang]} onClick={changeLang}>
      {locales.map((locale) => (
        <Menu.Item key={locale.code}>
          <span role="img" aria-label={locale.name}>
            {LanguagesIcon[locale.code] || '🇧🇷'}
          </span>{' '}
          {locale.name}
        </Menu.Item>
      ))}
    </Menu>
  );

  return (
    <HeaderDropdown overlay={langMenu} placement="bottomRight">
      <span className={classNames(styles.dropDown, className)}>
        <GlobalOutlined title={formatMessage({ id: 'navBar.lang' })} />
      </span>
    </HeaderDropdown>
  );
};

export default SwitchLanguages;
